package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.dto.iot.IotMsgNotifyData;
import com.zzyl.nursing.service.IDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备数据Service业务层处理
 * 
 * @author jingchenghjiang
 * @date 2025-09-23
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    /**
     * 查询设备数据
     * 
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     * 
     * @param dto 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceDataPageReqDto dto)
    {
        return deviceDataMapper.selectDeviceDataList(dto);
    }

    /**
     * 新增设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     * 
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     * 
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     * 
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return deviceDataMapper.deleteById(id);
    }

    @Autowired
    private IDeviceService deviceService;

    @Override
    public void batchInsertDeviceData(IotMsgNotifyData dto) {
        //1.拿到设备id
        String deviceId = dto.getHeader().getDeviceId();
        Device device = deviceService.lambdaQuery()
                .eq(Device::getIotId, deviceId)
                .one();
        if(device==null){
            //设备不存在
            log.error("设备不存在：{}",deviceId);
            return;
        }
        //批量保存到数据库
        List<DeviceData> list= new ArrayList<>();//把list填充进去
        Map<String, Object> map = dto.getBody().getServices().get(0).getProperties();
        String eventTime = dto.getBody().getServices().get(0).getEventTime();
        // 定义时间格式器，用于解析字符串
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssZ");

        // 处理可能的Z结尾（UTC标识），替换为+0000便于解析
        String adjustedTimeStr = eventTime.replace("Z", "+0000");

        // 先解析为LocalDateTime，再关联UTC时区转换为Instant
        LocalDateTime utcLocalDateTime = LocalDateTime.parse(adjustedTimeStr, formatter);
        Instant instant = utcLocalDateTime.toInstant(ZoneOffset.UTC);

        // 转换为东八区(Asia/Shanghai)的LocalDateTime
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, ZoneId.of("Asia/Shanghai"));
        map.forEach((k,v)->{
            DeviceData data = new DeviceData();
            data.setDeviceName(device.getDeviceName());
            data.setIotId(device.getIotId());
            data.setProductKey(device.getProductKey());
            data.setProductName(device.getProductName());
            data.setFunctionId(k);
            data.setAccessLocation(device.getRemark());
            data.setLocationType(device.getLocationType());
            data.setDeviceDescription(device.getDeviceDescription());
            data.setDataValue(v+"");
            data.setAlarmTime(localDateTime);
            list.add(data);
        });
        saveBatch(list);

    }
}
